const nodemailer = require('nodemailer');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// 邮箱配置 - 从环境变量获取或使用默认值
const emailConfig = {
  host: process.env.EMAIL_HOST || 'smtp.qq.com',
  port: process.env.EMAIL_PORT || 465,
  secure: process.env.EMAIL_SECURE === 'false' ? false : true,
  auth: {
    user: process.env.EMAIL_USER || '627841628@qq.com', // ⚠️ 修改为您的QQ邮箱
    pass: process.env.EMAIL_PASS || 'nttqgciijxyzbbjb' // ⚠️ 修改为您的QQ邮箱授权码
  }
};

console.log('邮箱配置:', {
  host: emailConfig.host,
  port: emailConfig.port,
  secure: emailConfig.secure,
  user: emailConfig.auth.user,
  // 不打印密码以保护安全
});

// 创建邮件发送器
const transporter = nodemailer.createTransport(emailConfig);

/**
 * 发送天气预警邮件
 * @param {Object} options - 邮件选项
 * @param {string} options.to - 收件人邮箱
 * @param {string} options.subject - 邮件主题
 * @param {string} options.username - 用户名
 * @param {string} options.location - 地点名称
 * @param {Array} options.warnings - 预警信息数组
 * @returns {Promise} - 发送结果
 */
exports.sendWarningEmail = async (options) => {
  try {
    // 检查必要参数
    if (!options.to || !options.warnings) {
      throw new Error('缺少必要参数');
    }

    // 默认值
    const subject = options.subject || '天气预警通知';
    const username = options.username || '用户';
    const location = options.location || '您关注的地点';

    // 生成HTML内容
    let warningHtml = '';
    if (options.warnings.length === 0) {
      warningHtml = '<p>当前没有任何预警信息。</p>';
    } else {
      warningHtml = options.warnings.map(warning => {
        const severityClass = getSeverityClass(warning.severityColor);
        return `
          <div class="warning-item ${severityClass}">
            <h3>${warning.title || '天气预警'}</h3>
            <p><strong>类型:</strong> ${warning.typeName}</p>
            <p><strong>发布时间:</strong> ${formatDate(warning.pubTime)}</p>
            <p><strong>生效时间:</strong> ${formatDate(warning.startTime)} 至 ${formatDate(warning.endTime)}</p>
            <p><strong>预警等级:</strong> <span class="severity ${severityClass}">${warning.severityColor || ''} ${warning.severity || ''}</span></p>
            <p><strong>发布单位:</strong> ${warning.sender}</p>
            <div class="warning-text">
              <p>${warning.text}</p>
            </div>
          </div>
        `;
      }).join('<hr/>');
    }

    // 完整的HTML模板
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <title>天气预警通知</title>
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 650px; margin: 0 auto; padding: 20px; }
          .header { text-align: center; margin-bottom: 30px; }
          .warning-item { border: 1px solid #ddd; border-radius: 5px; padding: 15px; margin-bottom: 20px; }
          .warning-text { background-color: #f9f9f9; padding: 10px; border-radius: 5px; margin-top: 10px; }
          .severity { font-weight: bold; padding: 3px 6px; border-radius: 3px; }
          .blue { border-left: 5px solid #0066cc; }
          .yellow { border-left: 5px solid #ffcc00; }
          .orange { border-left: 5px solid #ff9900; }
          .red { border-left: 5px solid #cc0000; }
          .white { border-left: 5px solid #cccccc; }
          .black { border-left: 5px solid #333333; }
          .green { border-left: 5px solid #00cc66; }
          hr { border: 0; height: 1px; background: #ddd; margin: 30px 0; }
          .footer { font-size: 12px; color: #666; text-align: center; margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px; }
        </style>
      </head>
      <body>
        <div class="header">
          <h1>天气预警通知</h1>
          <p>尊敬的 ${username}，以下是 ${location} 的天气预警信息</p>
        </div>
        
        <div class="warnings">
          ${warningHtml}
        </div>
        
        <div class="footer">
          <p>此邮件由系统自动发送，请勿回复。</p>
          <p>天气预警系统 &copy; ${new Date().getFullYear()}</p>
        </div>
      </body>
      </html>
    `;

    // 发送邮件
    const mailOptions = {
      from: `"天气预警系统" <${emailConfig.auth.user}>`,
      to: options.to,
      subject: subject,
      html: html
    };

    const info = await transporter.sendMail(mailOptions);
    console.log('预警邮件发送成功:', info.messageId);
    return { success: true, messageId: info.messageId };
  } catch (error) {
    console.error('预警邮件发送失败:', error);
    return { success: false, error: error.message };
  }
};

/**
 * 发送测试邮件
 * @param {string} to - 收件人邮箱
 * @returns {Promise} - 发送结果
 */
exports.sendTestEmail = async (to) => {
  try {
    const mailOptions = {
      from: `"天气预警系统" <${emailConfig.auth.user}>`,
      to: to,
      subject: '天气预警系统 - 测试邮件',
      html: `
        <div style="max-width: 600px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;">
          <h1 style="color: #333; text-align: center;">天气预警系统</h1>
          <p>这是一封测试邮件，用于验证邮件发送功能是否正常。</p>
          <p>如果您收到此邮件，说明天气预警系统的邮件发送功能工作正常。</p>
          <p style="color: #666; font-size: 12px; margin-top: 30px; border-top: 1px solid #eee; padding-top: 10px;">
            此邮件由系统自动发送，请勿回复。
          </p>
        </div>
      `
    };

    const info = await transporter.sendMail(mailOptions);
    console.log('测试邮件发送成功:', info.messageId);
    return { success: true, messageId: info.messageId };
  } catch (error) {
    console.error('测试邮件发送失败:', error);
    return { success: false, error: error.message };
  }
};

// 辅助函数 - 根据预警颜色获取对应的CSS类
function getSeverityClass(color) {
  if (!color) return '';
  
  const colorMap = {
    'Blue': 'blue',
    'Yellow': 'yellow',
    'Orange': 'orange',
    'Red': 'red',
    'White': 'white',
    'Black': 'black',
    'Green': 'green'
  };
  
  return colorMap[color] || '';
}

// 辅助函数 - 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return '未指定';
  
  try {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return dateStr;
  }
} 